package cn.cslg.weatherforecast;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.cslg.weatherforecast.config.Global;
import cn.cslg.weatherforecast.design.strategy.ClickOnAbout;
import cn.cslg.weatherforecast.design.strategy.ClickOnLogout;
import cn.cslg.weatherforecast.design.strategy.ClickOnMusic;
import cn.cslg.weatherforecast.design.strategy.Strategy;
import cn.cslg.weatherforecast.design.strategy.StrategyContext;
import cn.cslg.weatherforecast.service.MusicService;
import cn.cslg.weatherforecast.util.ServiceUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private ScrollView parentLayout;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private TextView city_tv;
    private TextView temp_tv;
    private TextView air_tv;
    private TextView weather_tv;
    private Button change_btn;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TextView humidity_tv;
    private TextView pressure_tv;
    private TextView suggestion_tv;

    OkHttpClient client = new OkHttpClient();
    private JSONObject jsonObject;

    private RecyclerView recyclerView;
    private List<DailyBean> dailyBeanList;

    SoundPool soundPool;
    int sound1;

    String run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {

            if (response.isSuccessful()) {
                String result = response.body().string();
                return result;
            } else {
                Toast.makeText(MainActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
                swipeRefreshLayout.setRefreshing(false);
                return null;
            }
        }
    }

    // 音乐服务
    private MusicService musicService;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicService = ((MusicService.MyBinder) service).getService();
            musicService.play();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (getSharedPreferences("data", MODE_PRIVATE).getBoolean("isLogin", false)) {
            findViews();
            init();
            setListeners();
        } else {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    }

    private void setListeners() {
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                init();
            }
        });
        change_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CityActivity.class);
                startActivityForResult(intent, 1);
            }
        });
    }

    private void init() {
        city_tv.setText(getSharedPreferences("data", MODE_PRIVATE).getString("cur_city", "北京"));
        dailyBeanList = new ArrayList<>();//清空上次数据
        new MyTask().execute(city_tv.getText().toString());
        //初始化RecyclerView
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        DailyAdapter adapter = new DailyAdapter(dailyBeanList);
        recyclerView.setAdapter(adapter);

        //加载SoundPool
        soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        sound1 = soundPool.load(this, R.raw.sd1, 1);
    }

    private void findViews() {
        parentLayout = findViewById(R.id.parent_layout);
        setBackground(getSharedPreferences("data", MODE_PRIVATE)
                .getInt("cur_background_index", 0));
        city_tv = findViewById(R.id.city_tv);
        temp_tv = findViewById(R.id.temp_tv);
        air_tv = findViewById(R.id.air_tv);
        weather_tv = findViewById(R.id.weather_tv);
        recyclerView = findViewById(R.id.recycler_view);
        change_btn = findViewById(R.id.change_btn);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        humidity_tv = findViewById(R.id.humidity_tv);
        pressure_tv = findViewById(R.id.pressure_tv);
        suggestion_tv = findViewById(R.id.suggestion_tv);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Context context = MainActivity.this;
        StrategyContext strategyContext = null;
        switch (item.getItemId()) {
            case R.id.about:
                soundPool.play(sound1, 1, 1, 1, 0, 1f);
                strategyContext = new StrategyContext(new ClickOnAbout());
                break;
            case R.id.background:
                int[] list = Global.bgList;
                int next = getCurBackgroundIndex() + 1;
                next = (next == list.length ? 0 : next);
                setBackground(next);
                break;
            case R.id.music:
                strategyContext = new StrategyContext(new ClickOnMusic());
                break;
            case R.id.logout:
                strategyContext = new StrategyContext(new ClickOnLogout());
                break;
        }
        if (strategyContext != null) {
            strategyContext.clickOperate(context);
        }
        return true;
    }

    public int getCurBackgroundIndex() {
        SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
        return sp.getInt("cur_background_index", 0);
    }

    public void setBackground(int next) {
        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
        editor.putInt("cur_background_index", next);
        editor.commit();
        parentLayout.setBackgroundResource(Global.bgList[next]);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("cur_city", data.getStringExtra("city"));
                    editor.commit();
                    init();
                }
        }
    }

    class MyTask extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] objects) {
            //工作线程不能更新UI控件
            try {
                return run(getResources().getString(R.string.url) + objects[0]);//传递给onPostExecute
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o != null) {
                try {
                    jsonObject = new JSONObject((String) o);
                    if (jsonObject.getString("msg").equals("ok")) {
                        jsonObject = jsonObject.getJSONObject("result"); //result
                        city_tv.setText(jsonObject.getString("city"));
                        temp_tv.setText(jsonObject.getString("temp"));
                        weather_tv.setText(jsonObject.getString("weather"));
                        air_tv.setText("空气" + jsonObject.getJSONArray("index").getJSONObject(5).getString("ivalue"));

                        humidity_tv.setText("风级:" + jsonObject.getString("windpower") + ",风力:" + jsonObject.getString("humidity"));
                        pressure_tv.setText("气压:" + jsonObject.getString("pressure"));
                        JSONArray indexArray = jsonObject.getJSONArray("index");
                        JSONObject temp0 = indexArray.getJSONObject(0);
                        JSONObject temp1 = indexArray.getJSONObject(1);
                        String suggestion = "生活建议:" + temp0.getString("detail")
                                + temp1.getString("detail");
                        suggestion_tv.setText(suggestion);

                        JSONArray jsonArray = jsonObject.getJSONArray("daily");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject temp = jsonArray.getJSONObject(i);
                            String date$day_weather$night_templow$day_temphigh = temp.getString("date").substring(5)
                                    + "$" + temp.getJSONObject("day").getString("weather")
                                    + "$" + temp.getJSONObject("night").getString("templow") + "/"
                                    + temp.getJSONObject("day").getString("temphigh") + "℃";
                            DailyBean dailyBean = new DailyBean(R.mipmap.ic_launcher, date$day_weather$night_templow$day_temphigh);
                            dailyBeanList.add(dailyBean);
                        }
                    }
                    Toast.makeText(MainActivity.this, "刷新成功", Toast.LENGTH_LONG).show();
                    swipeRefreshLayout.setRefreshing(false);
                    return;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            Toast.makeText(MainActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
            swipeRefreshLayout.setRefreshing(false);
        }
    }

}
